package com.chenxingnet.controller;


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.chenxingnet.dto.Cars;
import com.chenxingnet.dto.Department;
import com.chenxingnet.dto.Drivers;
import com.chenxingnet.dto.Waybills;
import com.chenxingnet.dto.vo.WaybillVo;
import com.chenxingnet.service.CarsService;
import com.chenxingnet.service.DepartmentService;
import com.chenxingnet.service.DriversService;
import com.chenxingnet.service.WaybillsService;
import com.google.gson.Gson;

@Controller
@RequestMapping("/waybills")
public class WaybillsController{
	
	@Resource
	private WaybillsService waybillsService;
	@Resource
	private DriversService driversService;
	
	@Resource
	private DepartmentService   departmentService;
	
	
	@Resource
	private CarsService   carsService;
	
	//小写的mm表示的是分钟HH:mm:ss
	private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH");
	
	@RequestMapping("/list")
	@ResponseBody
	public String list(Integer page , Integer rows){
		Integer startIndex = (page - 1) * rows;
		Map params = new HashMap();
		params.put("st" , startIndex);
		params.put("r" , rows);
		List<Map> list = waybillsService.findByProperty(params);
		Long cnt = waybillsService.countByProperty(params);
		Map result = new HashMap();
		result.put("total" , cnt);
		result.put("rows" , list);
		return new Gson().toJson(result);
	}
	
	@RequestMapping("/findByProperty")
	@ResponseBody
	public String findByProperty(HttpServletRequest request){
		Map params = new HashMap();
		Map<String,String[]> rparam = request.getParameterMap();
		Iterator itr = rparam.entrySet().iterator();
		while(itr.hasNext()){
			Map.Entry<String, String[]> me = (Map.Entry<String, String[]>)itr.next();
			if(me.getValue().length == 1){
				params.put(me.getKey(), me.getValue()[0]);
			}else{
				params.put(me.getKey(), me.getValue());
			}
			
		}
		if(params.containsKey("st")){
			params.put("st", new Integer(params.get("st").toString()));
		}
		if(params.containsKey("r")){
			params.put("r", new Integer(params.get("r").toString()));
		}
		List<Map> list = waybillsService.findByProperty(params);
		Long cnt = waybillsService.countByProperty(params);
		return new Gson().toJson(list);
	}
	
	@RequestMapping("/huiZong")
	public String huiZong(HttpServletRequest request,Model model,Integer page){
		int rows = 30;
		Map params = new HashMap();
		Map<String,String[]> rparam = request.getParameterMap();
		Iterator itr = rparam.entrySet().iterator();
		while(itr.hasNext()){
			Map.Entry<String, String[]> me = (Map.Entry<String, String[]>)itr.next();
			if(me.getValue().length == 1){
				params.put(me.getKey(), me.getValue()[0]);
			}else{
				params.put(me.getKey(), me.getValue());
			}
			
		}
		//利用page进行分页
		if(params.containsKey("page")){
			int st = (page-1)*rows;
			int r = rows;
			params.put("st",st);
			params.put("r", r);
		}else{
			page = 1;
			int st = (page-1)*rows;
			int r = rows;
			params.put("st",st);
			params.put("r", r);
		}
		List<Map> list = waybillsService.findByProperty(params);
		Long cnt = waybillsService.countByProperty(params);
		//设置页面相关数据
		Map pages = new HashMap();
		pages.put("totalCount", cnt);
		pages.put("pageNow", page);
		pages.put("totalPageCount", (int)Math.ceil(1.0*cnt/rows));
		model.addAttribute("accoutlist", list);
		model.addAttribute("page", pages);
		model.addAttribute("orderby",params.get("orderby"));
		return "huizong";
	}
	/**
	 * 转至新增运单信息页面
	 * @return
	 */
	@RequestMapping("/insertWaybill")
	public String insertWaybill(HttpServletRequest request,Model model){
		Integer deptid = Integer.valueOf(request.getParameter("deptid"));
		List<Department>   deps=  departmentService.showDept();
		List<Cars>    cars=  carsService.getAllCars();
		List<Drivers>   ds=  driversService.selectAll();
		List<String>      carsShiFas=new   ArrayList<String>(); 
		List<String>      carsShiFasRe=new   ArrayList<String>(); 
		for(int   a=0;a<cars.size();a++){
			carsShiFas.add(cars.get(a).getCcommence());
		}
         Set set = new  HashSet(); 
         for (String cd:carsShiFas) {
            if(set.add(cd)){
            	carsShiFasRe.add(cd);
            }
        }
     	model.addAttribute("carsShiFasRe", carsShiFasRe);
		model.addAttribute("ds", ds);
		model.addAttribute("deptid", deptid);
		model.addAttribute("deps", deps);
		return "yundandengji";
	}
	/**
	 * 转至修改运单页面
	 * @return
	 */
	@RequestMapping("/upWayJsp")
	public String upWayJsp(Integer wid,HttpServletRequest request,Model model){
		try {
			Integer deptid = Integer.valueOf(request.getParameter("deptid"));
			model.addAttribute("deptid", deptid);
		} catch (Exception e) {
			
		}
		Waybills way = waybillsService.selectById(wid);
		model.addAttribute("way", way);
		
		return "yundanupdate";
	}

	/**
	* @Title: /waybills/mobile_insertWaybill 
	*移动端运单状态请求
	 */
	@RequestMapping("/mobile_insertWaybill")
	public void mobile_insertWaybill(HttpServletRequest request,Model model,HttpServletResponse response){
		try {
				response.setHeader("Access-Control-Allow-Origin", "*");
				response.setContentType("application/json;charset=utf-8");
				JSONObject returnJson = new JSONObject();
				returnJson.put("falg","true");
			 
				Integer deptid = Integer.valueOf(request.getParameter("deptid"));
				List<Department>   deps=  departmentService.showDept();
				List<Cars>    cars=  carsService.getAllCars();
				List<Drivers>   ds=  driversService.selectAll();
				List<String>      carsShiFas=new   ArrayList<String>(); 
				List<String>      carsShiFasRe=new   ArrayList<String>(); 
				for(int   a=0;a<cars.size();a++){
					carsShiFas.add(cars.get(a).getCcommence());
				}
		         Set set = new  HashSet(); 
		         for (String cd:carsShiFas) {
		            if(set.add(cd)){
		            	carsShiFasRe.add(cd);
		            }
		        }
		         returnJson.put("carsShiFasRe", carsShiFasRe);
		         returnJson.put("ds", ds);
		         returnJson.put("deptid", deptid);
		         returnJson.put("deps", deps);
				
				response.getWriter().print(returnJson.toString());
		} catch (Exception e) {  e.printStackTrace();  }
	}
	
	
	
	
	@ResponseBody
	@RequestMapping("/getBonByCom")
	public List<Cars> getBonByCom(HttpServletRequest request,Model model){
		try {
			Integer deptid = Integer.valueOf(request.getParameter("deptid"));
			if(deptid != null){
				model.addAttribute("deptid", deptid);
			}
		} catch (Exception e) {
			
		}
		String com = request.getParameter("wcommence");
		List<Cars> carList = carsService.selectByCommon(com);
		return carList;
	}
	
	
	/**
	 * 新增运单信息
	 * @return
	 */
	@RequestMapping("/addWaybill")
	public String addWaybill(Waybills waybills,HttpServletRequest request,Model model,@RequestParam  MultipartFile... files){
		
		Integer deptid = Integer.valueOf(request.getParameter("deptid"));
		
		String str1 = request.getParameter("wdeparturetime1");
		String str2 = request.getParameter("westimatedtime1");
		String str3 = request.getParameter("wneartime1");
		String str4 = request.getParameter("winsurancetime1");
		
		Date wdeparturetime = null;
		Date westimatedtime = null;
		Date wneartime = null;
		Date winsurancetime = null;
		try {
			if(!str1.equals("")){
				wdeparturetime = sdf.parse(str1);
				waybills.setWdeparturetime(wdeparturetime);
			}
			if(!str2.equals("")){
				westimatedtime = sdf.parse(str2);
				waybills.setWestimatedtime(westimatedtime);
			}
			if(!str3.equals("")){
				wneartime = sdf.parse(str3);
				waybills.setWneartime(wneartime);
			}
			if(!str4.equals("")){
				winsurancetime = sdf.parse(str4);
				waybills.setWinsurancetime(winsurancetime);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String nameId = request.getParameter("nameId");
		//存入的登记者id
		waybills.setWdept(Integer.valueOf(nameId));
		//利润=厂家结算-驾驶员结算-商业保险-强险金额-临牌金额
		waybills.setWprofit(waybills.getWfactory().subtract(waybills.getWpilot()).subtract(waybills.getWcommercial()).subtract(waybills.getWcoerce()).subtract(waybills.getWamount()));
		
		waybills.setWtimeout("未结算");
		waybills.setWcreationtime(new Date());
		waybills.setWreportstart("1");
		waybills.setWinsurance(new  BigDecimal(1));
		waybillsService.addAppWaybill(waybills);
		model.addAttribute("deptid", deptid);
		return "redirect:/waybills/insertWaybill";
		/*return "redirect:/waybills/showWaybill?pageNow=1&deptid="+deptid;*/
	}
	
	
	/**
	* @Title: /waybills/mobile_addWaybill 
	*移动端运单登记
	 */
	@RequestMapping("/mobile_addWaybill")
	public void mobile_addWaybill(HttpServletRequest request,Model model,HttpServletResponse response){
		try {
				System.out.println("mobile_addWaybill");
				response.setHeader("Access-Control-Allow-Origin", "*");
				response.setContentType("application/json;charset=utf-8");
				JSONObject returnJson = new JSONObject();
				returnJson.put("falg","true");
				String deptid = request.getParameter("deptid");
				System.out.println(deptid);
				String wcommence = request.getParameter("wcommence");
				String wbourn = request.getParameter("wbourn");
				String wvehicle = request.getParameter("wvehicle");
				String wvin = request.getParameter("wvin");
				String wactuate = request.getParameter("wactuate");
				
				String str1 = request.getParameter("wdeparturetime1");
				String str2 = request.getParameter("westimatedtime1");
				String str3 = request.getParameter("wneartime1");
				String str4 = request.getParameter("winsurancetime1");
				
				String wtransport = request.getParameter("wtransport");
				BigDecimal wfactory = new BigDecimal(request.getParameter("wfactory"));
				BigDecimal wpilot = new BigDecimal(request.getParameter("wpilot"));
				BigDecimal wcommercial = new BigDecimal(request.getParameter("wcommercial"));
				BigDecimal wcoerce = new BigDecimal(request.getParameter("wcoerce"));
				BigDecimal wamount = new BigDecimal(request.getParameter("wamount"));
				String wremark = request.getParameter("wremark");
				
				
				Waybills  waybills  = new  Waybills();
				Date wdeparturetime = null;
				Date westimatedtime = null;
				Date wneartime = null;
				Date winsurancetime = null;
				try {
					if(!str1.equals("")){
						wdeparturetime = sdf.parse(str1);
						waybills.setWdeparturetime(wdeparturetime);
					}
					if(!str2.equals("")){
						westimatedtime = sdf.parse(str2);
						waybills.setWestimatedtime(westimatedtime);
					}
					if(!str3.equals("")){
						wneartime = sdf.parse(str3);
						waybills.setWneartime(wneartime);
					}
					if(!str4.equals("")){
						winsurancetime = sdf.parse(str4);
						waybills.setWinsurancetime(winsurancetime);
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
				waybills.setDeptid(Integer.valueOf(deptid));
				waybills.setWcommence(wcommence);
				waybills.setWbourn(wbourn);
				waybills.setWvehicle(wvehicle);
				waybills.setWvin(wvin);
				waybills.setWactuate(wactuate);
				waybills.setWtransport(wtransport);
				waybills.setWfactory(wfactory);
				waybills.setWpilot(wpilot);
				waybills.setWcommercial(wcommercial);
				waybills.setWcoerce(wcoerce);
				waybills.setWamount(wamount);
				waybills.setWremark(wremark);
				
				String nameId = request.getParameter("nameId");
				//存入的登记者id
				waybills.setWdept(Integer.valueOf(nameId));
				//利润=厂家结算-驾驶员结算-商业保险-强险金额-临牌金额
				waybills.setWprofit(waybills.getWfactory().subtract(waybills.getWpilot()).subtract(waybills.getWcommercial()).subtract(waybills.getWcoerce()).subtract(waybills.getWamount()));
				waybills.setWtimeout("未结算");
				waybills.setWcreationtime(new Date());
				waybills.setWreportstart("1");
				//判断厂商是否结算：1未结算，2已结算
				waybills.setWinsurance(new  BigDecimal(1));
				int   resu=	waybillsService.addAppWaybill(waybills);
				returnJson.put("result",resu);//返回插入结果。
				response.getWriter().print(returnJson.toString());
		} catch (Exception e) {  e.printStackTrace();  }
	}
	
	
	/**
	 * 查询对应城市的运单信息
	 * @return
	 */
	@RequestMapping("/showWaybill")
	public String showWaybill(HttpServletRequest request,Model model){
		
		Integer deptid = Integer.valueOf(request.getParameter("deptid"));
		List<WaybillVo> waybillVo = waybillsService.selectByDeptid(deptid,request,model);
		model.addAttribute("waybillVo", waybillVo);
		model.addAttribute("deptid", deptid);
		return "yundanzhuangtai";
	}
	
	

	//  用户名重复检测    ajax
	@RequestMapping("/ajaxChangshangjiesuanshi")
	@ResponseBody
	public Map<String,Object> ajaxChangshangjiesuanshi(HttpServletRequest request,Model model,  HttpServletResponse httpServletResponse){
		httpServletResponse.setCharacterEncoding("UTF-8");
		String   index1=request.getParameter("index1");
		String[] args=request.getParameterValues("checkbox");
		int res = 0;
		if(index1==null||index1.equals("")){
			for (String str : args) {
				res=	waybillsService.updateChangshangjiesuanshi(Integer.parseInt(str));
			}
		}else{
			res=	waybillsService.updateChangshangjiesuanshi(Integer.parseInt(index1));
		}
     	Map<String, Object> result=new HashMap<String, Object>();
		result.put("result",res);
		return  result;
	}
	
	
	

	/**
	* @Title: /waybills/mobile_showWaybill 
	*移动端运单状态请求
	 */
	@RequestMapping("/mobile_showWaybill")
	public void mobile_showWaybill(HttpServletRequest request,Model model,HttpServletResponse response){
		try {
				response.setHeader("Access-Control-Allow-Origin", "*");
				response.setContentType("application/json;charset=utf-8");
				JSONObject returnJson = new JSONObject();
				returnJson.put("falg","true");
			 
				Integer deptid = Integer.valueOf(request.getParameter("deptid"));
				List<WaybillVo> waybillVo = waybillsService.mobSelectByDeptid(deptid,request,model);
				
				int ws = waybillsService.getCountByWS(deptid);
				int song = waybillsService.getCountByS(deptid);
				int chs = waybillsService.getCountByCHS(deptid);
				int sg = waybillsService.getCountbYSG(deptid);
				
				returnJson.put("ws", ws);
				returnJson.put("song", song);
				returnJson.put("chs", chs);
				returnJson.put("sg", sg);
				
				returnJson.put("waybillVo", waybillVo);
				returnJson.put("deptid", deptid);
				returnJson.put("page", request.getAttribute("mobilePage"));
				
				response.getWriter().print(returnJson.toString());
		} catch (Exception e) {  e.printStackTrace();  }
	}
	/**
	 * 删除数据修改状态为0
	 * @param wid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/delWayById")
	public String delWayById(Integer wid,HttpServletRequest request,Model model){
		Integer deptid = 0;
		try {
			deptid = Integer.valueOf(request.getParameter("deptid"));
			if(deptid != null){
				model.addAttribute("deptid", deptid);
			}
		} catch (Exception e) {
			
		}
		waybillsService.deleteWaybill(wid);
		
		return "redirect:/waybills/showWaybill?pageNow=1&deptid="+deptid;
	}
	
	/**
	 * 修改运单信息
	 * @return
	 */
	@RequestMapping("/updateWaybill")
	public String updateWaybill(Waybills waybills,HttpServletRequest request,Model model){
		System.out.println("wid:"+waybills.getWid());
		Integer deptid = 0;
		try {
			deptid = Integer.valueOf(request.getParameter("deptid"));
			if(deptid != null){
				model.addAttribute("deptid", deptid);
			}
		} catch (Exception e) {
			
		}
		
		String wdepartureStr = request.getParameter("wdeparturetime1");
		String westimatedStr = request.getParameter("westimatedtime1");
		String wnearStr = request.getParameter("wneartime1");
		String winsuranceStr = request.getParameter("winsurancetime1");
		
		Date wdeparturetime = null;
		Date westimatedtime = null;
		Date wneartime = null;
		Date winsurancetime = null;
		try {
			if(!wdepartureStr.equals("")){
				wdeparturetime = sdf.parse(wdepartureStr);
				waybills.setWdeparturetime(wdeparturetime);
			}
			if(!westimatedStr.equals("")){
				westimatedtime = sdf.parse(westimatedStr);
				waybills.setWestimatedtime(westimatedtime);
			}
			if(!wnearStr.equals("")){
				wneartime = sdf.parse(wnearStr);	
				waybills.setWneartime(wneartime);
			}
			if(!winsuranceStr.equals("")){
				winsurancetime = sdf.parse(winsuranceStr);
				waybills.setWinsurancetime(winsurancetime);
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		waybills.setWcreationtime(new Date());
		
		waybillsService.updateWaybill(waybills);
		model.addAttribute("deptid", deptid);
		return "redirect:/waybills/showWaybill?pageNow=1&deptid="+deptid;
	}

	

	
	@RequestMapping("/demo")
	public String demo(HttpServletRequest request,Model model){
		Integer deptid = 1;
		List<Department>   deps=  departmentService.showDept();
		List<Cars>    cars=  carsService.getAllCars();
		List<Drivers>   ds=  driversService.selectAll();
		List<String>      carsShiFas=new   ArrayList<String>(); 
		List<String>      carsShiFasRe=new   ArrayList<String>(); 
		for(int   a=0;a<cars.size();a++){
			carsShiFas.add(cars.get(a).getCcommence());
		}
         Set set = new  HashSet(); 
         for (String cd:carsShiFas) {
            if(set.add(cd)){
            	carsShiFasRe.add(cd);
            }
        }
     	model.addAttribute("carsShiFasRe", carsShiFasRe);
		model.addAttribute("ds", ds);
		model.addAttribute("deptid", deptid);
		model.addAttribute("deps", deps);
		return "demo";
	}
}
